package com.xinqi.modules.sys.role.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinqi.common.base.enums.YesNoEnum;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.response.PageInfo;
import com.xinqi.common.base.response.Param;
import com.xinqi.common.base.response.R;
import com.xinqi.common.mybatis.utils.Pages;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.common.satoken.utils.LoginHelper;
import com.xinqi.modules.sys.role.convert.RoleConvert;
import com.xinqi.modules.sys.role.domain.RoleEntity;
import com.xinqi.modules.sys.role.dto.req.AddUserRoleDTO;
import com.xinqi.modules.sys.role.dto.req.RoleCreateDTO;
import com.xinqi.modules.sys.role.dto.req.RoleDeleteDTO;
import com.xinqi.modules.sys.role.dto.req.RoleQueryDTO;
import com.xinqi.modules.sys.role.dto.req.RoleStatusUpdateDTO;
import com.xinqi.modules.sys.role.dto.req.RoleUpdateDTO;
import com.xinqi.modules.sys.role.dto.rsp.RoleResultDTO;
import com.xinqi.modules.sys.role.manager.RoleManager;
import com.xinqi.modules.sys.role.service.RoleService;
import com.xinqi.modules.sys.role.service.UserRoleService;
import com.xinqi.modules.user.user.client.UserClient;
import com.xinqi.modules.user.user.dto.rsp.UserResultDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统角色服务层实现
 *
 * @author: linkai
 * @date: 2023/04/01
 */
@Validated
@Service("roleService")
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private final RoleConvert roleConvert;

    private final RoleManager roleManager;

    private final UserRoleService userRoleService;

    private final UserClient userClient;

    /**
     * 分页查询 系统角色数据
     */
    @Override
    @DS("slaver")
    public PageInfo<RoleResultDTO> page(Param pageable, RoleQueryDTO query) {
        IPage<RoleEntity> page = roleManager.page(Pages.page(pageable), wrapper(query));
        return Pages.convert(page, roleConvert::convert);
    }

    /**
     * 查询 系统角色数据
     */
    @Override
    public List<RoleResultDTO> find(RoleQueryDTO query) {
        return roleManager.list(wrapper(query)).stream()
            .map(roleConvert::convert).collect(Collectors.toList());
    }

    private LambdaQueryWrapper<RoleEntity> wrapper(RoleQueryDTO query) {
        LambdaQueryWrapper<RoleEntity> wrapper = Queries.lambda();
        Queries.accept(query.getId(), v -> wrapper.eq(RoleEntity::getId, v));
        Queries.accept(query.getName(), v -> wrapper.like(RoleEntity::getName, v));
        return wrapper;
    }

    /**
     * 根据id查询 系统角色数据
     */
    @Override
    public RoleResultDTO findById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return Optional.ofNullable(roleManager.findById(id)).map(roleConvert::convert).orElse(null);
    }

    /**
     * 新增 系统角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(@Valid RoleCreateDTO dto) {
        RoleEntity entity = roleConvert.create(dto);
        check(dto.getName(), null);
        roleManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据id修改 系统角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateById(@Valid RoleUpdateDTO dto) {
        Optional.ofNullable(roleManager.getById(dto.getId()))
            .orElseThrow(() -> CommonErrors.BAD_REQUEST.asException("数据不存在"));
        check(dto.getName(), dto.getId());
        RoleEntity entity = roleConvert.update(dto);
        return roleManager.updateById(entity);
    }

    /**
     * 根据id删除 系统角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(Long id) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(id), "ID不能为空");
        return roleManager.removeById(id);
    }

    /**
     * 根据id删除 系统角色数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteById(RoleDeleteDTO dto) {
        return deleteById(dto.getId());
    }

    private void check(String name, Long oldId) {
        CommonErrors.BAD_REQUEST.check(!isExistName(name, oldId), "角色名称重复");
    }

    @Override
    public boolean isExistName(String name, Long oldId) {
        LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleEntity::getName, name);
        queryWrapper.eq(RoleEntity::getIsDelete, YesNoEnum.NO.ordinal());
        if (oldId != null) {
            queryWrapper.ne(RoleEntity::getId, oldId);
        }
        return roleManager.count(queryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addUserRole(AddUserRoleDTO dto) {
        userRoleService.addUserRole(dto);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(RoleStatusUpdateDTO dto) {
        return roleManager.updateStatus(dto);
    }

    @Override
    public List<RoleResultDTO> findUserRole(Long userId) {
        return roleManager.findUserRole(userId);
    }

    @Override
    public List<RoleResultDTO> findCurrentUserRole() {
        UserResultDTO user = R.as(userClient.findById(LoginHelper.getUserId()));
        if (Objects.equals(YesNoEnum.YES.ordinal(), user.getIsSuperAdmin())) {
            return this.find(new RoleQueryDTO());
        }
        return roleManager.findUserRole(user.getId());
    }

}
